const app = getApp();

Page({
  data: {
    albumpnum: 4,  //效果图最大上传图片
    goodsnum: 6, //商品图最大图片数
    roomId: "",
    groupTitle: "",
    totalPrice: "",
    preImgtopfileds: {},
    coverImg: "",
    resultData: {},
    goodsImgtopfileds: {},
    styleArr: [
    ],
    selectIndex: [
      { sureid: false },
      { sureid: false },
      { sureid: false },
      { sureid: false },
      { sureid: false },
      { sureid: false },
      { sureid: false },
      { sureid: false },
      { sureid: false },
    ],
    roomArr: [
    ],
    roomIndex: [
      { sureid: false },
      { sureid: false },
      { sureid: false },
      { sureid: false },
      { sureid: false },
      { sureid: false },
      { sureid: false },
      { sureid: false },
      { sureid: false },
    ],
    styleChoose: [],
    roomChoose: [],
    preImgtop: '', //上传头图预览图;
    preImgtopId: 0, //上传头图id
    roomType: [
    ],
    roomItem: "",
    roomItems: [],
    num: -1,
    curIndex: "",
    preImgsAbout: [], // 上传活动相关图片，最多5张；
    preImgsAboutId: [], //上传活动相关图片，最多5张Id；
    newText: "",
  },
  onLoad: function (option) {
    this.data.option = option;
    this.setData({ option: option })
    var id = this.data.option.id;
    console.log("onshow 11111111111111111111111111111")
    this.getList(id); 
  },
  onShow() {
    // this.data.preImgtopfileds=[];
    // this.data.goodsImgtopfileds = [];
    var that = this;
    console.log(that.data.preImgtopfileds,"show111111111111");
    console.log("=============onshow=====", this.data.goodsImgtopfileds)
    var id = this.data.option.id;
    this.getList(id); 
  },
  
  getList: function (id) {
    var _this = this;
    getApp().request({
      url: getApp().api.styleList,
      method: "post",
      success: function (e) {
        console.log("获取styleList的数据 e：", e);
        if (e.code === 1) {
          var styleArr = _this.data.styleArr;
          var newArr = e.data.list;
          if (styleArr.length > 0) {
            _this.setData({
              styleArr: styleArr,
              styleArrFlag:true
            })
          } else {
            _this.setData({
              styleArr: e.data.list,
              styleArrFlag: true
            })
          }
        } else {
          wx.showToast({
            title: '错误!',
          })
        }
      },
      fail: function (e) {
        console.log(e);
      }
    });
    getApp().request({
      url: getApp().api.roomList,
      method: "post",
      success: function (e) {
        console.log("获取roomList的数据 e：", e);
        if (e.code === 1) {
          var roomArr = _this.data.roomArr;
          var newArr = e.data.list;
          if (roomArr.length > 0) {
            for (let i = 0; i < roomArr.length; i++) {
              newArr[i] = roomArr[i]
            }
            _this.setData({
              roomArr: newArr,
              roomArrFlag:true
            })
          } else {
            _this.setData({
              roomArr: e.data.list,
              roomArrFlag: true
            })
          }
        } else {
          wx.showToast({
            title: '错误!',
          })
        }
      },
      fail: function (e) {
        console.log(e);
      }
    });
    var timed = setInterval(function(){
      if (_this.data.styleArrFlag && _this.data.roomArrFlag) {
        _this.getInfo(id); 
        clearInterval(timed)
      }  
    },30)
  },
  
  getInfo:function(id){
    var _this = this;
    //获取套餐详情
    getApp().request({
      url: getApp().api.groupDetail,
      method: "post",
      data: { id: id },
      success: function (res) {
        console.log("获取套餐详情 res：", res);
        var obj = {
          groupTitle: res.name,
          totalPrice: parseInt(res.amount),
          coverImg: res.cover_img,
          styleArr: res.style,
          roomArr: res.room
        };

        var styleArr = _this.data.styleArr;

        var objstyleArr = obj.styleArr;
        //console.log();
        styleArr.forEach(function (v) {
          var id = v.id;
          objstyleArr.forEach(function (v2) {
            if (v2.id === id) {
              v.checked = true;
            }
          })
        });
        obj.styleArr = styleArr;

        var roomArr = _this.data.roomArr;

        var objroomArr = obj.roomArr;
        roomArr.forEach(function (v) {
          var id = v.id;
          objroomArr.forEach(function (v2) {
            if (v2.id === id) {
              v.check = true;
              v.count = v2.count
            }
          })
        });
        obj.roomArr = roomArr;


        var roomType = [];
        roomArr.forEach(function (v, k) {
          if (v.check) {
            var info = {
              id: v.id,
              room: v.name,
              count:v.count
            }
            roomType.push(info);
          }
        })
        obj.roomType = roomType;

        var preImgtopfileds = _this.data.preImgtopfileds;
        var imglist = res.opus;
        imglist.forEach(function(v){
          if(!preImgtopfileds[v.room]){
            preImgtopfileds[v.room] = [];
          }
          var info = {
            preImgtop: v.file_url,
            preImgtopId: v.image_id
          }
          preImgtopfileds[v.room].push(info);
        });
        obj.preImgtopfileds = preImgtopfileds;
        console.log(preImgtopfileds);

        var goodsImgtopfileds = _this.data.goodsImgtopfileds;
        // console.log(_this.data.goodsImgtopfileds,"图片")
        var goodslist = res.goods;
        console.log("goodslist", goodslist)
        goodslist.forEach(function (v) {
          console.log("V",v)
          if (!goodsImgtopfileds[v.room]) {
            console.log("---------------",goodsImgtopfileds)
            goodsImgtopfileds[v.room] = [];
          }
          var info = {
            price:v.price,
            cover_pic:v.cover_pic,
            number: v.number,
            id:v.id
          }
          goodsImgtopfileds[v.room].push(info);
        });
        console.log(goodsImgtopfileds);
        obj.goodsImgtopfileds = goodsImgtopfileds;
        
        obj.groupid = res.id;
        _this.setData(obj);
      }
    })
    
  },
  //添加自定义选项
  addRoom: function (value) {
    var self = this;
    console.log(value)
    self.setData({
      newText: value
    })
    let pages = getCurrentPages();
    console.log(pages);
    let prevPage = pages[pages.length - 2];
    if (prevPage.data.newText !== "") {
      var arr = prevPage.data.roomArr;
      var arr2 = prevPage.data.roomIndex;
      var text = prevPage.data.newText;
      var newtext = { room: text };
      var newsureid = { sureid: true };
      arr.push(newtext);
      arr2.push(newsureid)
      self.setData({
        roomArr: arr,
        roomIndex: arr2,
      })
      console.log(prevPage.data.roomArr)
      console.log(prevPage.data.roomIndex)
    }
  },
  //图片区域
  chooseFirst: function (e) {
    this.setData({
      num: -1,
    })
  },
  chooseRoom: function (e) {
    console.log(e.currentTarget.dataset.item)
    this.setData({
      roomItem: e.currentTarget.dataset.item.room,
      roomId: e.currentTarget.dataset.roomid,
      num: e.currentTarget.dataset.id,
      curIndex: e.currentTarget.dataset.id,

    })
  },
  /* 删除已选择的图片 */
  delImg: function (e) {
    let index = e.target.dataset.index;
    let imgArr = this.data.preImgsAbout;
    imgArr.splice(index, 1);
    this.setData({
      preImgsAbout: imgArr
    })
  },
  //标题
  input1: function (e) {
    // console.log(e)
    var value = e.detail.value
    this.setData({
      groupTitle: value
    })
  },
  //总价
  input2: function (e) {
    var value = e.detail.value
    this.setData({
      totalPrice: value
    })
  },
  linkWarehouse: function () {
    // var num = this.data.goodsnum;
    // var len = 0;
    // let imglist = this.data.goodsImgtopfileds[this.data.roomId];
    // if (imglist) {
    //   len = imglist.length;
    // }
    // if (len === num) {
    //   return wx.showToast({
    //     title: '最多允许' + num + '张'
    //   })
    // }
    var goodsImgtopfileds = this.data.goodsImgtopfileds;
    var roomId = this.data.roomId;
    var json = {};
    // goodsImgtopfileds[roomId].forEach(function(v){
    //   json[v.id] = v;
    // });
    // wx.setStorageSync("listarr", json)
    wx.navigateTo({
      url: "/pages1/productWarehouse1/productWarehouse1"
    })
  },
  isChoose3: function (e) {
    let index = e.currentTarget.dataset.index;
    let roomArr = this.data.roomArr;
    roomArr[index].check = !(roomArr[index].check);
    this.setData({
      roomArr: roomArr
    });

    var roomType = [];
    roomArr.forEach(function (v, k) {
      if (v.check) {
        var info = {
          id: v.id,
          room: v.name,
          count:v.count
        }
        roomType.push(info);
      }
    })
    console.log("nnnnnnnnnnnnnnnnnnnnnnnnn")
    this.setData({
      roomType: roomType
    })
  },
  //选择风格
  isChoose1: function (e) {
    let index = e.currentTarget.dataset.index;
    var styleArr = this.data.styleArr;
    styleArr[index].checked = !(styleArr[index].checked);
    this.setData({
      styleArr: styleArr
    })
  },
  //选择空间
  isChoose2: function (e) {
    console.log(e)
    let index = e.currentTarget.dataset.roomindex; //当前点击元素的自定义数据，这个很关键
    let sureid = e.currentTarget.dataset.sureid;
    let roomItem = e.currentTarget.dataset.item;
    let roomIndex = this.data.roomIndex;  //取到data里的styleIndex
    roomIndex[index].sureid = !roomIndex[index].sureid;  //点击就赋相反的值
    this.setData({
      roomIndex: roomIndex  //将已改变属性的json数组更新
    })
    if (sureid == false) {
      let arr = this.data.roomChoose;
      arr.push(roomItem);
      this.setData({
        roomChoose: arr
      })
    } else if (sureid == true) {
      let index = e.currentTarget.dataset.roomindex;
      let imgArr = this.data.roomChoose;
      imgArr.splice(index, 1);
      this.setData({
        roomChoose: imgArr
      })
    }
    console.log(this.data.roomChoose,"123456")
    var roomType = [];
    this.data.roomChoose.forEach(function (v, k) {
      var info = {
        id: k,
        room: v
      }
      roomType.push(info);
    })
    this.setData({
      roomType: roomType
    })
  },  
  /* 图片上传选择作品库 */
  uploadImg1: function (e) {
    let num = e.currentTarget.dataset.num;
    let flag = e.currentTarget.dataset.flag;
    let preImgsAbout = this.data.preImgsAbout;
    wx.chooseImage({
      count: num == 5 ? num - preImgsAbout.length : num, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: (res) => {
        let tempFilePaths = res.tempFilePaths;
        wx.showLoading({
          mask: true,
          title: '正在上传...',
        })
        console.log(tempFilePaths);
        //  this.uploadimgs({
        //    url: getApp().api.default.mini_upload_image,
        //    path: tempFilePaths,
        //    flag: flag,
        //  })
      },
      fail: (res) => {
        wx.navigateTo({
          url: "/pages1/chooseProduct/chooseProduct"
        })
      }
    })
  },
  /* 图片上传 */
  uploadImg: function (e) {
    let num = e.currentTarget.dataset.num;
    let flag = e.currentTarget.dataset.flag;
    let preImgsAbout = this.data.preImgsAbout;
    var count = num == 5 ? num - preImgsAbout.length : num
    if (flag === 'cover') {
      count = 1;
    }
    wx.chooseImage({
      count: count, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: (res) => {
        let tempFilePaths = res.tempFilePaths;
        wx.showLoading({
          mask: true,
          title: '正在上传...',
        })
        this.uploadimgs({
          url: getApp().api.default.mini_upload_image,
          path: tempFilePaths,
          flag: flag,
        })

      },
    })
  },
  /* 图片上传 */
  uploadimgs: function (data) {
    var that = this,
      i = data.i ? data.i : 0,//当前上传的哪张图片
      success = data.success ? data.success : 0,//上传成功的个数
      fail = data.fail ? data.fail : 0;//上传失败的个数
    let flag = data.flag;
    var preImgtopfileds = that.data.preImgtopfileds;
    var coverImg = that.data.coverImg;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      header: {
        'Content-Type': 'multipart/form-data',
        'WX-Token': wx.getStorageSync('TOKEN'),
      },
      name: 'file',//这里根据自己的实际情况改
      formData: {	//这里是上传图片时一起上传的数据
        minapp: 'weixinminapp'
      },
      success: (resp) => {
        let result = resp.data ? JSON.parse(resp.data) : { code: 0 };
        if (result.code == 0) {
          success++;//图片上传成功，图片上传成功的变量+1
          if (flag == 'top') {
            //  this.setData({
            //    preImgtop: result.data.url
            //  })
            //  this.setData({
            //    preImgtopId: result.data.id
            //  });
            var roomItem = preImgtopfileds[that.data.roomId];
            if (!roomItem) {
              preImgtopfileds[that.data.roomId] = []
              roomItem = preImgtopfileds[that.data.roomId];
            }
            //var roomItem = that.data.roomItem;
            preImgtopfileds[that.data.roomId].push({
              preImgtop: result.data.url,
              preImgtopId: result.data.id
            });
            that.setData({
              preImgtopfileds: preImgtopfileds
            })
          } else if (flag == 'qrcode') {
            this.setData({
              preImgQrcode: result.data.url
            })
            this.setData({
              preImgQrcodeId: result.data.id
            })
          } else if (flag == 'about') {
            let arr = this.data.preImgsAbout;
            let fileIds = this.data.preImgsAboutId;
            arr.push(result.data.url);
            fileIds.push(result.data.id);
            this.setData({
              preImgsAbout: arr
            })
            this.setData({
              preImgsAboutId: fileIds
            })
            console.log(this.data.preImgsAbout)
            console.log(this.data.preImgsAboutId)
          } else if (flag == 'cover') {
            coverImg = result.data.url;
            that.setData({
              coverImg: coverImg
            })
          }
        } else {
          fail++; //图片上传失败，图片上传失败的变量+1
          console.log('fail:' + i + "fail:" + fail);
        }
      },
      fail: (res) => {
        fail++;//图片上传失败，图片上传失败的变量+1
      },
      complete: () => {
        i++;//这个图片执行完上传后，开始上传下一张
        if (i == data.path.length) {   //当图片传完时，停止调用
          wx.hideLoading();
          if (fail > 0) {
            wx.showToast({
              icon: 'none',
              title: '成功' + success + '张，失败' + fail + '张',
            });
          } else {
            wx.showToast({
              title: '图片上传完成',
            })
            console.log(that.data.preImgtopfileds);
          }

        } else {	//若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimgs(data);
        }

      }
    });
  },

  //点击确认保存
  saveGroupMsg: function (e) {
    var t = this, value;
    console.log(this)
    // getApp().core.showLoading({
    // 	title: "正在保存",
    // 	mask: !0
    // });
    var pages = getCurrentPages();
    var curpage = pages[pages.length - 1];
    // console.log(curpage);
    //return console.log(images);
    var roomChoose = [];
    var roomChooseid = [];
    this.data.roomArr.forEach(function (v) {
      if (v.check) {
        roomChoose.push(v.name);
        roomChooseid.push(v.id);
      }
    });
    var goodsImgtopfileds = this.data.goodsImgtopfileds;
    var preImgtopfileds = this.data.preImgtopfileds;
    var images = [];
    var goods = [];
    roomChooseid.forEach(function (v) {
      if (preImgtopfileds[v]) {
        preImgtopfileds[v].forEach(function (v2) {
          var newinfo = {
            room: v,
            id: v2.preImgtopId
          }
          images.push(newinfo);
        })
      }
      if (goodsImgtopfileds[v]) {
        goodsImgtopfileds[v].forEach(function (v2) {
          var newinfo = {
            room: v,
            id: v2.id,
            price: v2.price
          }
          goods.push(newinfo);
        })
      }
    });

    var goodsImgtopfileds = this.data.goodsImgtopfileds;
    var images = [];
    var goods = [];
    roomChooseid.forEach(function (v) {
      if (preImgtopfileds[v]) {
        preImgtopfileds[v].forEach(function (v2) {
          var newinfo = {
            room: v,
            id: v2.preImgtopId
          }
          images.push(newinfo);
        })
      }
      if (goodsImgtopfileds[v]) {
        goodsImgtopfileds[v].forEach(function (v2) {
          // console.log("V2----",v2)
          var newinfo = {
            room: v,
            id: v2.id,
            number: v2.number,
            price:v2.price            
          }
          goods.push(newinfo);
        })
      }
    });

    var styleChoose = [];
    // console.log(this.data.styleArr);
    this.data.styleArr.forEach(function(v){
      if (v.checked) {
        styleChoose.push(v.id);
      }
    })

    var _d = {
      id:this.data.groupid,
      cover_img: this.data.coverImg,
      name: t.data.groupTitle,
      amount: t.data.totalPrice,
      style: JSON.stringify(styleChoose),
      room: JSON.stringify(roomChooseid),
      images: JSON.stringify(images),
      goods: JSON.stringify(goods)
    };
    if (!_d.name) {
      wx.showToast({
        title: '请输入套餐名称',
      })
      return;
    }
    if (!_d.amount) {
      wx.showToast({
        title: '请输入套餐总价',
      })
      return;
    }
    console.log("------------商品-----------",_d.goods)
    getApp().request({
      url: getApp().api.saveGroup,
      method: "post",
      data: _d,
      success: function(e) {
        console.log("保存的商品----------------",_d)
				console.log("获取首页数据 e：", e);
        wx.navigateBack({

        })
				// getApp().core.hideLoading();
        //  0 == e.code && getApp().core.showModal({
				// 	title: "提示",
				// 	content: e.msg,
				// 	showCancel: !1,
				// 	success: function(e) {
				// 		e.confirm && wx.redirectTo({
				// 			url:"/pages1/homePage/homePage"
				// 		});
				// 	}
				// })
				// 1 == e.code && getApp().core.showModal({
				// 	title: "提示",
				// 	content: e.msg,
				// 	showCancel: !1,
				// })
			},
      fail: function (e) {
        console.log(e);
      }
    });
  },

  //点击确认保存
  // saveGroupMsg: function() {
  // 	var t = this;
  // 	getApp().core.showLoading({
  // 		title: "正在保存",
  // 		mask: !0
  // 	});
  // 	var pages = getCurrentPages();
  // 	var curpage = pages[pages.length - 1];
  // 	console.log(curpage)
  // 	getApp().request({
  // 		url: getApp().api.saveGroup,
  // header: {
  //   'Content-Type': 'multipart/form-data',
  // },
  // 		method: "post",
  // 		data: {
  // 			name: "套餐名称",
  // 	id:16,
  // 	style: [101,102],
  // 	room:[201,202],
  // 	images:[{id:1,room:201}],
  // 	goods:[{id:1,room:201}]
  // 			
  // 		},
  // 		success: function(e) {
  // 			console.log("获取首页数据 e：", e);
  // 			getApp().core.hideLoading(), 0 == e.code && getApp().core.showModal({
  // 				title: "提示",
  // 				content: e.msg,
  // 				showCancel: !1,
  // 				success: function(e) {
  // 					e.confirm && wx.redirectTo({
  // 						url:"/pages1/homePage/homePage"
  // 					});
  // 				}
  // 			})
  // 			1 == e.code && getApp().core.showModal({
  // 				title: "提示",
  // 				content: e.msg,
  // 				showCancel: !1,
  // 			})
  // 		},
  // 		fail: function(e){
  // 			console.log(e);
  // 		}
  // 	});
  // },
  preImgcancel(e) { //效果图片取消
    var preImgtopfileds = this.data.preImgtopfileds;
    var roomId = this.data.roomId;
    var index = e.currentTarget.dataset.index;
    preImgtopfileds[roomId].splice(index, 1);
    this.setData({
      preImgtopfileds: preImgtopfileds
    });
  },
  goodsImgcancel(e) { //产品图片取消
    var goodsImgtopfileds = this.data.goodsImgtopfileds;
    var roomId = this.data.roomId;
    var index = e.currentTarget.dataset.index;
    goodsImgtopfileds[roomId].splice(index, 1);
    this.setData({
      goodsImgtopfileds: goodsImgtopfileds
    });
  },
  workspic() { //作品库选择
    console.log("111");
    wx.navigateTo({
      url: "/pages1/chooseProduct/chooseProduct"
    })

  },
  albumpic(e) { //相册选择
    var param = e.detail;
    let num = parseInt(param.num);
    let flag = param.flag;
    let preImgsAbout = this.data.preImgsAbout;
    let imglist = this.data.preImgtopfileds[this.data.roomId];
    var len = 0;
    if (imglist) {
      len = imglist.length;
    }
    if (len === num) {
      return wx.showToast({
        title: '最多允许' + num + '张',
        icon:"none"
      })
    }
    wx.chooseImage({
      count: num - len, // 默认num - len张
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: (res) => {
        let tempFilePaths = res.tempFilePaths;
        wx.showLoading({
          mask: true,
          title: '正在上传...',
        })
        this.uploadimgs({
          url: getApp().api.default.mini_upload_image,
          path: tempFilePaths,
          flag: flag,
        })
      },
    })
  },
  //跳转到商品详情
  linkGoods: function (e) {
    var self = this;
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/pages1/commodityDetail/commodityDetail?id=" + id
    })
  },
})